package com.central.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.central.common.enums.ResourceType;
import com.central.task.mapper.QuoteResourceMapper;
import com.central.task.mapper.ResourceInfoMapper;
import com.central.task.model.QuoteResource;
import com.central.common.model.ResourceInfo;
import com.central.task.service.IResourceManageService;
import com.central.common.feign.FileService;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.common.utils.UserRoleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Tindy
 * @date 2021/11/29
 * @describe
 */
@Slf4j
@Service
public class ResourceManageServiceImpl extends SuperServiceImpl<ResourceInfoMapper, ResourceInfo> implements IResourceManageService {

    @Autowired
    private QuoteResourceMapper quoteResourceMapper;
    @Autowired
    private FileService fileService;

    @Override
    public List<ResourceInfo> findChilds(Long id) {
        List<ResourceInfo> resourceInfos = baseMapper.selectList(new QueryWrapper<ResourceInfo>().eq("parent_id", id));
        return resourceInfos;
    }

    @Override
    public QuoteResource findQuote(Long id) {
        return quoteResourceMapper.selectOne(new QueryWrapper<QuoteResource>().eq("resource_id", id));
    }

    @Override
    public List<ResourceInfo> findOnes(Long proId, Long parentId) {
        return baseMapper.selectList(new QueryWrapper<ResourceInfo>().eq("pro_id", proId).eq("parent_id", parentId));
    }

    @Transactional
    @Override
    public Result delete(SysUser user, Long id) {
        ResourceInfo resourceInfo = getById(id);
        if (!resourceInfo.getProId().equals(user.getCurrentProjectId())) return Result.failed("操作失败：" + "该文件非当前项目，无权限");
        if (resourceInfo.getResourceType() == ResourceType.DIR) {
            //如果删除目标时文件夹,判断该目录下是否存在其他文件或子目录
            List<ResourceInfo> resourceInfos = findChilds(id);
            if (resourceInfos.size() > 0) {
                return Result.failed("操作失败：" + "该目录存在其他文件或子目录");
            } else {
                if(resourceInfo.getCreator().equals(user.getUsername()) || UserRoleUtil.checkProAdmin(user.getProRoles())){
                    removeById(id);
                }else {
                    return Result.failed("操作失败："+"非该文件的创建者或项目管理员无权限操作");
                }
                return Result.succeed("操作成功");
            }
        } else {
            //删除资源前,判断该文件是否被引用
            QuoteResource quoteResource = findQuote(id);
            if (quoteResource != null) {
                return Result.failed("操作失败：该资源被引用，" + quoteResource.getMsg());
            }
            if(resourceInfo.getCreator().equals(user.getUsername()) || UserRoleUtil.checkProAdmin(user.getProRoles())){
                removeById(id);
                fileService.delQuote(resourceInfo.getUrlQuoteId());
            }else {
                return Result.failed("操作失败："+"非该文件的创建者或项目管理员无权限操作");
            }
            return Result.succeed("操作成功");
        }
    }

    @Transactional
    @Override
    public Result create(SysUser user, ResourceInfo resourceInfo) {
        Long quoteId=null;
        try{
            if(resourceInfo.getParentId()==null) resourceInfo.setParentId(0l);
            if(resourceInfo.getParentId()!=0l){
                ResourceInfo parentPath = baseMapper.selectById(resourceInfo.getParentId());
                if(parentPath==null) return Result.failed("操作失败："+"父目录不存在");
                if(!parentPath.getProId().equals(user.getCurrentProjectId())) return Result.failed("操作失败：" + "该父目录文件夹非当前项目，无权限");
                if(parentPath.getResourceType()!=ResourceType.DIR) return Result.failed("操作失败：" + "该父目录文件夹非文件夹类型");
            }
            ResourceInfo resourceInfo2 = baseMapper.selectOne(new QueryWrapper<ResourceInfo>().eq("pro_id", user.getCurrentProjectId()).eq("parent_id", resourceInfo.getParentId()).eq("name", resourceInfo.getName()));
            if(resourceInfo2!=null){
                return Result.failed("操作失败："+"该同名文件（夹）已经存在");
            }
            resourceInfo.setId(null);
            resourceInfo.setProId(user.getCurrentProjectId());
            resourceInfo.setCreator(user.getUsername());
            if(resourceInfo.getFileUrl()!=null){
                quoteId = fileService.quoteFile(resourceInfo.getFileUrl(), "项目:" + resourceInfo.getProId() + "的资源文件，" + resourceInfo.getName());
                resourceInfo.setUrlQuoteId(quoteId);
            }
            save(resourceInfo);;
            return Result.succeed("操作成功");
        }catch (Exception e){
            if(quoteId!=null){
                fileService.delQuote(quoteId);
            }
            throw e;
        }
    }

    @Override
    public Long quoteResource(Long resourceId, String msg) {
        QuoteResource quoteResource = new QuoteResource();
        quoteResource.setResourceId(resourceId);
        quoteResource.setMsg(msg);
        quoteResourceMapper.insert(quoteResource);
        return quoteResource.getId();
    }

    @Override
    public void delQuotes(List<Long> ids) {
        quoteResourceMapper.deleteBatchIds(ids);
    }

    @Override
    public List<ResourceInfo> findResByIds(List<Long> ids) {
        if(!CollectionUtils.isEmpty(ids)){
            return  baseMapper.findResByIds(ids);
        }else {
            return new ArrayList<>();
        }
    }
}
